<template>
  <div id="manageQuestionView">
    <a-form :model="searchParams" layout="inline" style="margin-top: 10px">
      <a-form-item field="title" label="名称" style="min-width: 240px">
        <a-input
          v-model="searchParams.title"
          placeholder="请输入名称"
          style="background: white"
          allow-clear
        />
      </a-form-item>

      <a-form-item class="form_style">
        <a-button type="primary" @click="searchQuestion">提交</a-button>
        <a-button type="primary" @click="resetSearch" style="margin-left: 5px">
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total
      }"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
      style="margin-top: 20px"
    >
      <!-- 操作列模板 -->
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doQuestion(record)">做题</a-button>
        </a-space>
      </template>

      <!-- 标签模板 -->
      <template #tags="{ record }">
        <a-tag
          v-for="(tag, index) in record.tags"
          :key="index"
          color="green"
          style="margin-right: 5px"
        >
          {{ tag }}
        </a-tag>
      </template>

      <!-- 通过率列自定义模板 -->
      <template #passRate="{ record }">
        <span v-if="record">
          {{ record.acceptedNum || 0 }}/{{ record.submitNum || 0 }} ({{
            calculatePassRate(record.acceptedNum, record.submitNum)
          }}%)
        </span>
        <span v-else>0</span>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { Question, QuestionControllerService } from '../../../generated'
import message from '@arco-design/web-vue/es/message'
import { onBeforeRouteUpdate, useRouter } from 'vue-router'
import { Input } from '@arco-design/web-vue'

const router = useRouter()
const tableRef = ref()
const dataList = ref<any[]>([])
const total = ref(0)
const searchParams = ref({
  pageSize: 5,
  current: 1,
  title: ''
})

const loadData = async () => {
  try {
    const res = await QuestionControllerService.listQuestionByPageUsingPost(
      searchParams.value
    )

    if (res.code === 0 && res.data) {
      //回调数据
      console.log(res.data)
      total.value = res.data.total
      // 正确遍历 records 数组进行日期格式化
      dataList.value = res.data.records.map((record: any) => ({
        ...record,
        createTime: record.createTime.slice(0, 10) // 提取 yyyy-MM-dd
      }))
    } else {
      message.error(`加载失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    message.error('网络请求异常')
  }
}

// 添加通过率计算方法
const calculatePassRate = (acceptedNum: number, submitNum: number) => {
  if (!submitNum || submitNum === 0) return 0
  return Math.round((acceptedNum / submitNum) * 100)
}

// 列配置
const columns = [
  { title: 'ID', dataIndex: 'id', width: 150 },
  { title: '标题', dataIndex: 'title', ellipsis: true, width: 100 },
  {
    title: '标签',
    slotName: 'tags',
    width: 150
  },
  {
    title: '通过率',
    slotName: 'passRate', // 使用自定义插槽
    width: 100
  },
  { title: '创建时间', dataIndex: 'createTime', width: 200 },
  {
    title: '操作',
    slotName: 'optional',
    width: 100,
    fixed: 'right'
  }
]

// 更新题目
const doQuestion = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`
  })
}

//当点击页号时,触发事件
const handlePageChange = (page: any) => {
  searchParams.value.current = page
  loadData()
}

//当点击页面大小时,触发事件
const handlePageSizeChange = (size: any) => {
  console.log(size)
}

//执行查询操作
const searchQuestion = () => {
  loadData()
}

//点击按钮，重置查询参数
const resetSearch = () => {
  searchParams.value.title = ''
  loadData()
}

// 初始化加载数据
onMounted(() => loadData())
</script>

<style scoped>
#manageQuestionView {
  max-width: 1280px;
  margin: 0 auto;
}
</style>
